package q1780_areAlmostEqual;

public class Solution {
    /*
    仅执行一次字符串交换能否使两个字符串相等
    直接遍历并记录即可 最后检查是否恰好两个字符不同且可以交换
     */
    public boolean areAlmostEqual(String s1, String s2) {
        if (s1.equals(s2)) return true;
        int diff = 0, idx1 = -1, idx2 = -1;
        for (int i = 0; i < s1.length(); i++) {
            if (s1.charAt(i) != s2.charAt(i)) {
                ++diff;
                if (diff > 2) {
                    return false;
                } else if (idx1 == -1) {
                    idx1 = i;
                } else {
                    idx2 = i;
                }
            }
        }
        if (diff != 2) return false;
        return s1.charAt(idx1) == s2.charAt(idx2) && s1.charAt(idx2) == s2.charAt(idx1);
    }
}
